package com.jrx.anytxn.transaction.timer.job.coupon.step;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jrx.anytxn.common.constant.Constants;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.BeanUtils;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.customer.constant.CouponConstant;
import com.jrx.anytxn.customer.constant.CustomerConstant;
import com.jrx.anytxn.customer.entity.CmCustomerExtInfo;
import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.customer.entity.CmCustomerRightInfo;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.entity.TlCouponDetail;
import com.jrx.anytxn.customer.entity.TlRightsExchangeLog;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerFirstLevelMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerSecondLevelMapper;
import com.jrx.anytxn.customer.service.IRightsExchangeLogService;
import com.jrx.anytxn.customer.util.Md5Utils;
import com.jrx.anytxn.feign.api.response.UserInfoRes;
import com.jrx.anytxn.feign.api.service.IUserApiService;
import com.jrx.anytxn.feign.gateway.bean.ApiResponse;
import com.jrx.anytxn.feign.gateway.bean.Card;
import com.jrx.anytxn.feign.gateway.request.CouponRequest05;
import com.jrx.anytxn.feign.gateway.response.CouponResponse05;
import com.jrx.anytxn.feign.gateway.service.IOuterGatewayService;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrActivityInfo;
import com.jrx.anytxn.param.entity.PrCardRollDetailInfo;
import com.jrx.anytxn.param.entity.PrRightsAndInterests;
import com.jrx.anytxn.param.service.cardRoll.ICardRollService;
import com.jrx.anytxn.param.service.rights.IPrActivityInfoService;
import com.jrx.anytxn.param.service.rights.IPrRightsAndInterestsService;
import com.jrx.anytxn.param.utils.ActivityUtils;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanMainInfo;
import com.jrx.anytxn.transaction.service.ILoanMainInfoService;
import com.jrx.anytxn.transaction.service.ISmsService;
import com.jrx.anytxn.transaction.timer.config.CouponConfig;
import com.jrx.anytxn.transaction.timer.job.coupon.dto.CustomerRightsDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * ClassName CouponSharingProcessor
 *
 * @author lujianyou zebin.zhang
 * @version 2.0
 * @description 分享消费送权益 processor
 * @date 2022/03/03 14:42
 **/
@Service
@Slf4j
public class CouponSharingProcessor implements ItemProcessor<CmCustomerExtInfo, CustomerRightsDTO> {

    private static final String mobilePattern = "^[1]([3-9])[0-9]{9}$";
    private static final String PREFIX_REDIS_KEY = "batch_mgm_";

    @Autowired
    private CouponConfig couponConfig;
    @Autowired
    private ILoanMainInfoService loanMainInfoService;
    @Autowired
    private IPrActivityInfoService activityInfoService;
    @Autowired
    private IPrRightsAndInterestsService rightsAndInterestsService;
    @Autowired
    private ExtCmCustomerSecondLevelMapper customerSecondLevelMapper;
    @Autowired
    private ISegmentService segmentService;
    @Autowired
    private IRightsExchangeLogService rightsExchangeLogService;
    @Autowired
    private IOuterGatewayService outerGatewayService;
    @Autowired
    private ExtCmCustomerFirstLevelMapper customerFirstLevelMapper;
    @Autowired
    private ICardRollService iCardRollService;
    @Autowired
    private ISmsService smsService;
    @Autowired
    private IUserApiService userApiService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public CustomerRightsDTO process(CmCustomerExtInfo item) throws Exception {
        PrActivityInfo activityInfo = activityInfoService.getByTenantIdAndActivityId(Constants.DEFAULT_TENANT_ID,
                couponConfig.getActivity().getNewUserSharedConsumeFirstActivityId());
        if (Objects.isNull(activityInfo)) {
            log.info("未匹配到相关活动信息：{}", activityInfo.getActivityId());
            return null;
        }

        // 增加活动截止日期判断，yyyy-MM-dd
        String todayStr = DateUtils.format(new Date(), "yyyy-MM-dd");
        log.info("活动ID：{}，当前日期：{}, 活动生效日期（含）：{}，失效日期（含）：{}", activityInfo.getActivityId(), todayStr,
                activityInfo.getEffectiveDate(), activityInfo.getExpireDate());
        if (!checkActivityTime(todayStr, activityInfo)) {
            return null;
        }

        log.info("当前活动生效中，活动ID：{}", activityInfo.getActivityId());

        try {
            CustomerRightsDTO customerRightsDTO = executeProcess(item, activityInfo);
            return customerRightsDTO;
        } catch (Exception e) {
            log.info("邀新有礼发放优惠券异常:{}", e);
            return null;
        }
    }


    private CustomerRightsDTO executeProcess(CmCustomerExtInfo item, PrActivityInfo activityInfo) throws Exception {
        /**
         * 1、获取推荐人信息
         * 2、查看推荐人是否已发放此分享此人发放的优惠券
         * 3、被推荐人是否有消费数据
         * 4、发放优惠券并同时发送相关短信
         */
        log.info("邀新用户消费送券 item:{}", JSONObject.toJSONString(item));

        //api查询参数组装
        Map<String, String> mapReq = new HashMap<>(8);
        mapReq.put("tenantId", item.getTenantId());
        mapReq.put("channelNo", item.getChannel());
        mapReq.put("userId", item.getUserId());
        UserInfoRes userInfoRes = null;
        try {
            ApiResponse<UserInfoRes> response = userApiService.queryInviteInfo(JSON.toJSONString(mapReq));
            userInfoRes = response.getData();
            if (BeanUtils.checkForNull(userInfoRes)) {
                log.error("请求api-server的邀新信息查询接口返回值存在null，信息为：{}", userInfoRes);
                return null;
            }
        } catch (Exception e) {
            log.info("调用anyApi-Server超时 {}", e);
            return null;
        }

        if (!userInfoRes.isRecommenderRegister()) {
            log.info("推荐人未注册兴安花，不进行后续逻辑");
            return null;
        }

        final String userCreditTime = userInfoRes.getCreditTime();
        log.info("被邀请人首次兴安花授信日期：{}, 活动生效日期（含）：{}，失效日期（含）：{}", activityInfo.getActivityId(), userCreditTime,
                activityInfo.getEffectiveDate(), activityInfo.getExpireDate());
        if (!checkActivityTime(userCreditTime, activityInfo)) {
            log.info("被邀请人首次授信日期不在活动时间内，不发送权益");
            return null;
        }

        // 推荐人手机号码
        final String recommenderCode = userInfoRes.getRecommenderMobile();
        // 被推荐人客户号
        final String recommendedCustomerId = item.getCustomerId();
        //租户号
        final String tenantId = item.getTenantId();

        if (StringUtils.isEmpty(recommenderCode)) {
            log.info("根据api查询，该客户首笔授信没有推荐人，不进行处理，客户id：{}", recommendedCustomerId);
            return null;
        }
        if (!Pattern.matches(mobilePattern, recommenderCode)) {
            log.info("推荐人编号:{} 不是手机号", recommenderCode);
            return null;
        }

        //被邀请人与邀请人手机号校验
        CmCustomerSecondLevel inviteUser = customerSecondLevelMapper.selectByCustomerIdAndChannel(recommendedCustomerId,
                Constants.DEFAULT_CHANNEL, Constants.DEFAULT_TENANT_ID);
        if (inviteUser == null) {
            log.info("被邀请人查询客户二级信息表，查无数据，被邀请人客户id：{}", recommendedCustomerId);
            return null;
        }
        if (inviteUser.getMobile().equals(recommenderCode)) {
            log.info("被推荐人手机号不能和推荐人手机号一致,手机号：{}", recommenderCode);
            return null;
        }

        // 推荐人是否激活兴安花标识，默认激活
        boolean recommenderActiveFlag = true;
        // 根据手机号查询客户信息
        CmCustomerSecondLevel cmCustomerSecondLevel = customerSecondLevelMapper.selectByChannelAndMobileAndTenantId(
                Constants.DEFAULT_CHANNEL, recommenderCode, Constants.DEFAULT_TENANT_ID);
        if (cmCustomerSecondLevel == null) {
            recommenderActiveFlag = false;
            log.info("根据租户号:{}、渠道号:{}、手机号:{}查询客户二级信息表，查无数据", Constants.DEFAULT_TENANT_ID, Constants.DEFAULT_CHANNEL,
                    recommenderCode);
        }

        // 根据租户号、活动id、chargeAccount、被推荐人customerId
        List<TlRightsExchangeLog> rightsExchangeLogList = rightsExchangeLogService.listByCustomerPhoneAndRecommended(tenantId, recommenderCode, recommendedCustomerId);
        if (!rightsExchangeLogList.isEmpty()) {
            log.info("该邀新送券活动已派发,不再发券,推荐人手机号码：{}、被推荐人：{}", recommenderCode, recommendedCustomerId);
            return null;
        }

        // 查询被推荐人是有消费
        List<AmLoanMainInfo> loanMainInfoList =
                loanMainInfoService.listByCustomerIdAndLoanType(tenantId, recommendedCustomerId, "4", Constants.DEFAULT_PRODTCT_CODE);
        if (loanMainInfoList.isEmpty()) {
            log.info("被推荐人客户号:{}未有任何消费记录，不发权益。", recommendedCustomerId);
            return null;
        }

        CustomerRightsDTO customerRightsDTO = new CustomerRightsDTO();

        String rightsId = activityInfo.getRightsId();
        PrRightsAndInterests rightsAndInterests = rightsAndInterestsService.getByRightsId(tenantId, rightsId);

        long exchangeId = 0;
        try {
            exchangeId = segmentService.getId(CustomerConstant.TL_COUPON_DETAIL_INFO);
        } catch (SegmentException e) {
            throw new TxnBizException(TxnRespCode.GET_SEGMENT_ID_ERROR);
        }
        final String sceneOrderId = DateUtils.format(new Date(), "yyyyMMddHHmmss") + exchangeId + "";

        if (recommenderActiveFlag) {
            CmCustomerFirstLevel cmCustomerFirstLevel =
                    customerFirstLevelMapper.selectFirstLevelByOrgIdAndCusId(cmCustomerSecondLevel.getCustomerId(),
                            cmCustomerSecondLevel.getOrganizationId(), item.getTenantId());
            try {
                //请求参数组装
                PrCardRollDetailInfo rightsPassExtractReq = this.buildRightsPassExtractReq(rightsId, recommenderCode, sceneOrderId);

                //下单
                PrCardRollDetailInfo prCardRollDetailInfo = iCardRollService.rightsPassExtract(rightsPassExtractReq);

                //响应参数组装
                CouponResponse05 couponResponse = this.buildCouponResponse(prCardRollDetailInfo, recommenderCode, rightsAndInterests.getRightsCate());
                TlRightsExchangeLog rightsExchangeLog = generateRightsExchangeLogOnCreatingSuccess(couponResponse, exchangeId,
                        cmCustomerFirstLevel.getCustomerId(), cmCustomerFirstLevel.getChineseName(), rightsAndInterests,
                        sceneOrderId, recommenderCode, recommendedCustomerId, activityInfo.getActivityId());

                customerRightsDTO.setRightsExchangeLog(rightsExchangeLog);
            } catch (TxnBizException e) {
                log.info("下单异常：{}", e.getErrMsg());
                return null;
            }
            CmCustomerRightInfo cmCustomerRightInfo =
                    generateCustomerRightInfo(cmCustomerSecondLevel, activityInfo, rightsAndInterests);
            TlCouponDetail couponDetail =
                    generateCouponDetail(cmCustomerRightInfo, cmCustomerFirstLevel, recommendedCustomerId, recommenderCode);
            customerRightsDTO.setCmCustomerRightInfo(cmCustomerRightInfo);

            customerRightsDTO.setTlCouponDetail(couponDetail);
        } else {
            //尝试设置mgm缓存键值, 若不存在, 则缓存成功, 由另外一个分区进行if存在性校验(分区记录若存在, 则正常下单; 若不存在, else"兜底"逻辑处理)
            //"兜底"逻辑: 推荐人记录在当前分区和其他分区都不存在, 则仅记录到ExchangeLog中, 然后发送短信
            String rKey = PREFIX_REDIS_KEY + tenantId + recommendedCustomerId;
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(rKey, recommendedCustomerId);
            if (flag != null) {
                if (flag) {
                    redisTemplate.expire(rKey, 5, TimeUnit.MINUTES);
                    log.info("----往redis中插入一条数据：key:{} value:{}", rKey, recommendedCustomerId);
                    return null;
                }
                try {
                    //请求参数组装
                    PrCardRollDetailInfo rightsPassExtractReq = this.buildRightsPassExtractReq(rightsId, recommenderCode, sceneOrderId);

                    //下单
                    PrCardRollDetailInfo prCardRollDetailInfo = iCardRollService.rightsPassExtract(rightsPassExtractReq);

                    //响应参数组装
                    CouponResponse05 couponResponse = this.buildCouponResponse(prCardRollDetailInfo, recommenderCode, rightsAndInterests.getRightsCate());
                    TlRightsExchangeLog rightsExchangeLog = generateRightsExchangeLogOnCreatingSuccess(couponResponse,
                            exchangeId, Constants.DEFAULT_CUSTOMER_ID, Constants.DEFAULT_CUSTOMER_NAME, rightsAndInterests,
                            sceneOrderId, recommenderCode, recommendedCustomerId, activityInfo.getActivityId());

                    customerRightsDTO.setRightsExchangeLog(rightsExchangeLog);
                } catch (TxnBizException e) {
                    log.info("下单异常：{}", e.getErrMsg());
                    return null;
                }
            } else {
                return null;
            }
        }
        log.info("发券参数组装成功，发券客户手机号：{}，被邀请客户Id：{}", recommenderCode, recommendedCustomerId);
        // 发送邀新短信
        smsService.sendSmsMq(customerRightsDTO.getRightsExchangeLog(), TransBizConstant.SMS_TYPE_INVITE_NEW);
        return customerRightsDTO;
    }

    private CouponResponse05 buildCouponResponse(PrCardRollDetailInfo prCardRollDetailInfo, String recommenderCode, String orderType) {
        CouponResponse05 couponResponse = new CouponResponse05();
        couponResponse.setId(String.valueOf(prCardRollDetailInfo.getId()));
        couponResponse.setOrderState(CouponConstant.EXCHANGE_COUPON_ORDER_SUCCESS);
        couponResponse.setOrderCreateTime(DateUtils.format(new Date(), DateUtils.DATE_PATTERN));
        couponResponse.setCustomerPhone(recommenderCode);
        couponResponse.setOrderType("0");//默认值，均为卡密类型

        Card card = new Card();
        card.setCardNo(prCardRollDetailInfo.getCardNumber());
        card.setCardPassword(prCardRollDetailInfo.getPassWord());
        List<Card> cardList = new ArrayList<>();
        cardList.add(card);
        couponResponse.setCards(cardList);

        return couponResponse;
    }

    /**
     * 权益平台下单
     *
     * @param mobile
     * @param rightsAndInterests
     * @param customerId
     * @param chineseName
     * @return
     * @throws TxnBizException
     */
    private TlRightsExchangeLog order(String mobile, PrRightsAndInterests rightsAndInterests, String customerId,
                                      String chineseName, String recommendedCustomerId, String activityId) throws TxnBizException {
        // step2：下单京东E卡，获取卡密信息
        String sceneOrderId = System.currentTimeMillis() + "";
        String createCouponJson = generateCreateCouponReq(rightsAndInterests, mobile, sceneOrderId);
        ApiResponse<CouponResponse05> couponResponse05ApiResponse = new ApiResponse<>();

        try {
            couponResponse05ApiResponse = outerGatewayService.order(createCouponJson);
        } catch (Exception e) {
            log.info("权益平台下单失败 {}", e);
            throw new TxnBizException(9999, e.getMessage());
        }


        if (TxnRespCode.SUCCESS.getCode() != couponResponse05ApiResponse.getCode()) {
            throw new TxnBizException(couponResponse05ApiResponse.getCode(), couponResponse05ApiResponse.getMessage());
        }

        CouponResponse05 couponResponse05 = couponResponse05ApiResponse.getData();
        if (couponResponse05 == null || CustomerConstant.FAIL.equals(couponResponse05.getDealState())) {
            throw new TxnBizException(Integer.valueOf(couponResponse05.getBusCode()), couponResponse05.getBusMsg());
        }

        // 写权益资格兑换日志表
        return generateRightsExchangeLogOnCreatingSuccess(couponResponse05, null, customerId, chineseName, rightsAndInterests,
                sceneOrderId, mobile, recommendedCustomerId, activityId);
    }

    /**
     * 下单成功生产权益兑换流水记录
     */
    private TlRightsExchangeLog generateRightsExchangeLogOnCreatingSuccess(CouponResponse05 response05, Long exchangeId,
                                                                           String customerId, String chineseName, PrRightsAndInterests rightsAndInterests, String sceneOrderId,
                                                                           String mobile, String recommendedCustomerId, String activityId) throws TxnBizException {
        TlRightsExchangeLog rightsExchangeLog = new TlRightsExchangeLog();
        if (null == exchangeId) {
            try {
                rightsExchangeLog.setId(segmentService.getId(CustomerConstant.TL_COUPON_DETAIL_INFO));
            } catch (SegmentException e) {
                throw new TxnBizException(TxnRespCode.GET_SEGMENT_ID_ERROR);
            }
        } else {
            rightsExchangeLog.setId(exchangeId);
        }

        rightsExchangeLog.setTenantId(rightsAndInterests.getTenantId());
        rightsExchangeLog.setCustomerId(customerId);
        rightsExchangeLog.setChineseName(chineseName);
        rightsExchangeLog.setRightsId(rightsAndInterests.getRightsId());
        rightsExchangeLog.setRightsType(rightsAndInterests.getRightsType());
        rightsExchangeLog.setSceneId(CustomerConstant.SCENE_ID);
        rightsExchangeLog.setSceneOrderId(sceneOrderId);
        rightsExchangeLog.setCouponSystemOrderId(response05.getId());
        rightsExchangeLog.setFingerprint(response05.getCustomerFingerprint());
        rightsExchangeLog.setBuyQuantity((short) 1);
        rightsExchangeLog.setCouponName(rightsAndInterests.getRightsName());
        rightsExchangeLog.setUnitPrice(response05.getUnitPrice());
        rightsExchangeLog.setTotalPrice(response05.getTotalPrice());
        rightsExchangeLog.setOrderType(response05.getOrderType());
        rightsExchangeLog.setCustomerFingerprint(response05.getCustomerFingerprint());
        rightsExchangeLog.setCustomerPhone(response05.getCustomerPhone());
        rightsExchangeLog.setChargeAccount(mobile);
        rightsExchangeLog.setOrderState(response05.getOrderState());
        rightsExchangeLog.setOrderCreateTime(DateUtils.parseDate(response05.getOrderCreateTime()));
        rightsExchangeLog.setCreateTime(new Date());
        rightsExchangeLog.setCreateBy(Constants.DEFAULT_USER);
        rightsExchangeLog.setAppId("");
        rightsExchangeLog.setChannel(Constants.DEFAULT_CHANNEL);
        rightsExchangeLog.setLogoUrl(rightsAndInterests.getLogoUrl());
        rightsExchangeLog.setResJson(JSON.toJSONString(response05));
        rightsExchangeLog.setRecordVersionNumber(Constant.VERSION_NUMBER);
        rightsExchangeLog.setActivityId(activityId);
        rightsExchangeLog.setRecommended(recommendedCustomerId);
        rightsExchangeLog.setOrderCompleteTime(new Date());

        List<Card> cardList = response05.getCards();
        if (cardList != null && cardList.size() > 0) {
            Card card = cardList.get(0);
            rightsExchangeLog.setCardNo(card.getCardNo());
            rightsExchangeLog.setCardPassword(card.getCardPassword());
        }

        return rightsExchangeLog;
    }

    /**
     * 生成 2.5 下单请求字符串
     *
     * @param rightsAndInterests
     * @param mobile
     * @param sceneOrderId
     * @return
     */
    private String generateCreateCouponReq(PrRightsAndInterests rightsAndInterests, String mobile,
                                           String sceneOrderId) {
        CouponRequest05 request = new CouponRequest05();
        request.setMobile(mobile);
        request.setFingerprint(Md5Utils.hash(mobile));
        request.setCouponId(rightsAndInterests.getRightsId());
        request.setBuyQuantity(1);
        request.setChargeAccount(mobile);
        request.setSceneOrderId(sceneOrderId);
        return JSON.toJSONString(request);
    }

    private CmCustomerRightInfo generateCustomerRightInfo(CmCustomerSecondLevel customerSecondLevel, PrActivityInfo activityInfo,
                                                          PrRightsAndInterests rightsAndInterests) throws TxnBizException {
        CmCustomerRightInfo customerRightInfo = new CmCustomerRightInfo();

        try {
            customerRightInfo.setId(segmentService.getId(CustomerConstant.CM_CUSTOMER_RIGHT_INFO));
        } catch (SegmentException segmentException) {
            throw new TxnBizException(TxnRespCode.GET_SEGMENT_ID_ERROR);
        }
        customerRightInfo.setRightsId(rightsAndInterests.getRightsId());
        customerRightInfo.setTenantId(Constants.DEFAULT_TENANT_ID);
        customerRightInfo.setChannel(Constants.DEFAULT_CHANNEL);
        customerRightInfo.setCustomerId(customerSecondLevel.getCustomerId());
        customerRightInfo.setOrganizationId(Constants.DEFAULT_ORG_NUMBER);
        String rightsEffectivePeriod = activityInfo.getRightsEffectivePeriod();

        customerRightInfo.setEffectDate(ActivityUtils.getEffectiveDateFrom(rightsEffectivePeriod,
                DateUtils.parseDate(activityInfo.getEffectiveDate()), new Date()));
        customerRightInfo.setExpiresDate(ActivityUtils.getExpireDateFrom(rightsEffectivePeriod,
                DateUtils.parseDate(activityInfo.getExpireDate()), new Date()));
        customerRightInfo.setRightsType(rightsAndInterests.getRightsType());
        customerRightInfo.setRightsName(rightsAndInterests.getRightsName());

        customerRightInfo.setLoanId("");
        customerRightInfo.setAllowProducts(Constants.DEFAULT_PRODTCT_CODE);
        // 因为先前已经兑换了，所以此处为已使用
        customerRightInfo.setRightsStatus(CustomerConstant.RIGHTS_STATUS_1);

        Date now = new Date();
        customerRightInfo.setCreateTime(now);
        customerRightInfo.setUpdateTime(now);
        customerRightInfo.setUpdateBy(customerSecondLevel.getCustomerId());
        customerRightInfo.setRecordVersionNumber(Constant.VERSION_NUMBER);
        customerRightInfo.setActivityId(activityInfo.getActivityId());
        customerRightInfo.setCouponCate("");
        customerRightInfo.setRightsQuantity(1);
        customerRightInfo.setProductCode(Constants.DEFAULT_PRODTCT_CODE);
        customerRightInfo.setCycleUse(CouponConstant.CYCLE_USE_N);
        customerRightInfo.setSubChannel(customerSecondLevel.getSubChannel());

        return customerRightInfo;
    }

    private TlCouponDetail generateCouponDetail(CmCustomerRightInfo customerRightInfo,
                                                CmCustomerFirstLevel cmCustomerFirstLevel, String recommendedCustomerId, String mobile) throws TxnBizException {
        TlCouponDetail tlCouponDetail = new TlCouponDetail();
        String customerId = customerRightInfo.getCustomerId();
        try {
            tlCouponDetail.setId(segmentService.getId(CustomerConstant.TL_COUPON_DETAIL_INFO));
        } catch (SegmentException segmentException) {
            throw new TxnBizException(TxnRespCode.GET_SEGMENT_ID_ERROR);
        }
        tlCouponDetail.setTenantId(Constants.DEFAULT_TENANT_ID);
        tlCouponDetail.setOrganizationId(TransBizConstant.DEFAULT_ORG_ID);
        tlCouponDetail.setChannel(Constants.DEFAULT_CHANNEL);
        tlCouponDetail.setCustomerId(customerId);
        tlCouponDetail.setRecommended(recommendedCustomerId);

        tlCouponDetail.setRightsId(customerRightInfo.getRightsId());
        tlCouponDetail.setRightsName(customerRightInfo.getRightsName());
        tlCouponDetail.setRightsType(customerRightInfo.getRightsType());
        tlCouponDetail.setCustomerRightsId(customerRightInfo.getId());
        tlCouponDetail.setCouponSummaryId(0L);

        tlCouponDetail.setChineseName(cmCustomerFirstLevel.getChineseName());
        tlCouponDetail.setIdNumber(cmCustomerFirstLevel.getIdNumber());
        tlCouponDetail.setMobile(mobile);

        Date now = new Date();
        tlCouponDetail.setCreateTime(now);
        tlCouponDetail.setUpdateTime(now);
        tlCouponDetail.setUpdateBy(customerId);
        tlCouponDetail.setRecordVersionNumber(Constant.VERSION_NUMBER);
        tlCouponDetail.setActivityId(customerRightInfo.getActivityId());

        return tlCouponDetail;
    }

    public PrCardRollDetailInfo buildRightsPassExtractReq(String rightsId, String recommenderCode, String sceneOrderId) {
        //请求参数组装
        PrCardRollDetailInfo rightsPassExtractReq = new PrCardRollDetailInfo();
        rightsPassExtractReq.setTenantId(Constants.DEFAULT_TENANT_ID);
        rightsPassExtractReq.setCardRollId(rightsId);
        rightsPassExtractReq.setReceivePhone(recommenderCode);
        rightsPassExtractReq.setSceneId(sceneOrderId);

        return rightsPassExtractReq;
    }

    public boolean checkActivityTime(String time, PrActivityInfo activityInfo) {
        if (time.compareTo(activityInfo.getExpireDate()) > 0) {
            log.warn("当前活动已失效，活动ID：{}", activityInfo.getActivityId());
            return false;
        }

        if (time.compareTo(activityInfo.getEffectiveDate()) < 0) {
            log.warn("当前活动已失效，活动ID：{}", activityInfo.getActivityId());
            return false;
        }

        return true;
    }

}
